package cloudservernacos;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class EchoController {

    @GetMapping("/test-sentinel-resource")
    @SentinelResource(
            value = "test-sentinel-resource",
            blockHandler  = "blockHandler"
    )
    public String testSentinelResource(@RequestParam(required = false) String a) {
        return a;
    }

    // Block 异常处理函数，参数最后多一个 BlockException，其余与原函数一致.
    public String blockHandler (String a, BlockException e ) {
        log.warn("限流或者降级了",e);
        return "限流，或者降级了";
    }

    @GetMapping("/test-sentinel-fallback")
    @SentinelResource(
            value = "test-sentinel-fallback",
            fallback= "fallback"
    )
    public String testSentinelResourcef(@RequestParam(required = false) String a) {
        if (StringUtils.isEmpty(a)) {
            throw new IllegalArgumentException(" cannot be blank.");
        }
        return a;
    }

    // falback处理
    public String fallback(String a,Throwable throwable) {
        log.warn("限流，或者降级了",throwable);
        return "限流，或者降级了";
    }
}
